package dao

import (
	"blog_server/internal/model"
	"blog_server/pkg/app"
	"github.com/jinzhu/gorm"
	"time"
)

type Dao struct {
	dbEngine *gorm.DB
}

func New(db *gorm.DB) *Dao {
	return &Dao{dbEngine: db}
}

func (d *Dao) CountTag(name string, state uint8) (int, error)  {
	tag := model.Tag{Name: name, State: state}
	return tag.Count(d.dbEngine)
}

func (d *Dao) GetTagList(name string, state uint8, page uint8, pageSize int) ([]model.Tag, error)  {
	
	tag := model.Tag{Name: name, State: state}
	pageOffset := app.GetPageOffset(int(page), pageSize)
	return tag.List(d.dbEngine, pageOffset, pageSize)
}

func (d *Dao) CreateTag(name string, state uint8, createdBy string) error  {
	tag := model.Tag{Name: name, State: state, Model: &model.Model{CreatedBy: createdBy}}
	return tag.Create(d.dbEngine)
}

func (d *Dao) UpdateTag(ID uint32, name string, state uint8, modifiedBy string) error {
	tag := model.Tag{Name: name, State: state, Model: &model.Model{ID: ID, ModifiedBy: modifiedBy, ModifiedOn: time.Now()}}
	return tag.Update(d.dbEngine)
}

func (d *Dao) DeleteTag(id uint32) error {
	tag := model.Tag{Model: &model.Model{ID: id}}
	return tag.Delete(d.dbEngine)
}